<?php


namespace app\api\controller\xilujob;


use addons\xilujob\controller\WeixinMini;
use addons\xilujob\library\Upload;
use app\common\controller\xilujob\XilujobApi;
use app\common\model\xilujob\CompanyProfile;
use app\common\model\xilujob\EnterpriseInfo;
use app\common\model\xilujob\Member;
use app\common\model\xilujob\ResumeActionLog;
use app\common\model\xilujob\ResumeDownload;
use app\common\model\xilujob\ResumeFile;
use app\common\model\xilujob\ResumeViewLog;
use app\common\model\xilujob\UserCollection;
use app\common\model\xilujob\Resume AS ResumeModel;
use app\common\model\xilujob\XilujobUser;
use think\Exception;
use function fast\array_get;

class Resume extends XilujobApi
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];
    protected $restrictedActions = ['*'];


    public function lists() {
        $params = $this->request->param();
        $params['city_id'] = $this->cityId;
        $resumes = ResumeModel::searchResume($params, $this->company->id);
        //$resumes = $resumes->getCollection();
        $this->success('查询成功',$resumes);
    }

    /**@apiTitle (用户查看自己简历)
     * @param $id
     */
    public function detail($id) {
        $resume = ResumeModel::getResume($id,true);
        //$hasActionLog = ResumeActionLog::hasLog($this->auth->id,$resume->user_id,$resume->id);
//        if(config('site.hide_contact') && !$hasActionLog ) {
//            $resume->personal->mobile = substr($resume->personal->mobile,0,3).'********';
//            $resume->personal->email = $resume->personal->email?'**********':'';
//        }else {
//            $resume->personal->hide_mobile = 0;
//        }
        //$isFav = UserCollection::isFav($this->auth->id, $resume->id,UserCollection::TYPE_RESUME);
        //$isInterviewing = \app\common\model\xilujob\JobApply::isInterviewing($resume->user_id, $this->auth->id);
        //ResumeViewLog::viewResume($this->auth->id, $id);
        $this->success('',[
            'resume'=>$resume,
            //'is_fav'=>$isFav,
            //'is_interviewing'=>$isInterviewing,
            //'action_num'=>ResumeActionLog::getAvailableNum($this->auth->id),
            //'has_action_log' => $hasActionLog
        ]);
    }

    /**
     * @apiTitle (企业查看简历)
     * @param $id
     */
    public function resume_detail($id) {
        $resume = ResumeModel::getResume($id,true);
        $company = $this->auth->isLogin()?CompanyProfile::get(['user_id'=>$this->auth->id]):null;

        $hasActionLog = $company?ResumeActionLog::hasLog($company->id,$resume->user_id,$resume->id):false;
        if($resume->personal->hide_mobile == 1 || (get_addon_config('xilujob')['hide_contact'] && !$hasActionLog)) {
            $resume->personal->mobile = substr($resume->personal->mobile,0,3).'********';
            $resume->personal->email = $resume->personal->email?'**********':'';
        }
        if($company){
            $isFav = UserCollection::isFav($company->id, $resume->id,UserCollection::TYPE_RESUME);
            $isInterviewing = \app\common\model\xilujob\JobInterview::isInterviewing($resume->user_id,$company->id);
            $isApply = \app\common\model\xilujob\JobApply::where('resume_id',$id)->where('company_id',$company->id)->count();
            ResumeViewLog::viewResume($company->id, $id);
        }
        $resume = $resume->toArray();
        if($resume['hide_education'] == 1){
            $resume['educations'] = [];
        }
        $this->success('',[
            'resume'=>$resume,
            'is_fav'=>$isFav??false,
            'is_interviewing'=>$isInterviewing??false,
            'is_apply'=>$isApply??false,
            'action_num'=>$this->auth->isLogin()?EnterpriseInfo::getAvailableNum($this->auth->id,'resume_view'):0,
            'has_action_log' => $hasActionLog
        ]);
    }

    /**
     * @apiTitle (企业收藏简历)
     */
    public function toggle_fav() {
        $resumeId = $this->request->post('id');
        $company = CompanyProfile::get(['user_id'=>$this->auth->id]);
        $result = UserCollection::toggleFav($company->id, $resumeId, UserCollection::TYPE_RESUME);
        $this->success('',['is_fav'=>$result]);
    }

    /**
     * 人才推荐, 个人用户在个人中心的推荐
     */
    public function recommend_resumes() {
        $user = $this->auth->getUser();
        $params = $this->request->param();
        $params['city_id'] = $this->cityId;
        $company = CompanyProfile::get(['user_id'=>$user->id]);
        $resumes = ResumeModel::recommendResumes($company , $params);
        $this->success('查询成功', $resumes);
    }

    /**
     * 企业用户，
     */
    public function get_interview() {
        $xiluuser = XilujobUser::get(['user_id'=>$this->auth->id]);
        if($xiluuser->enterprise_model->audit_status != 1) {
            $this->error('企业审核通过后方可操作');
        }
        $hasAction = EnterpriseInfo::getAvailableNum($xiluuser->enterprise_model->id,'interview');
        if($hasAction<=0){
            $this->error("你的企业邀请面试次数已用完，请前往购买");
        }
        $resumeId = $this->request->param('resume_id');
        $resume = $resumeId?\app\common\model\xilujob\Resume::getResume($resumeId,true) : null;
        $this->success('查询成功',$resume);
    }

    /**
     * 企业用户，
     */
    public function get_contact() {
        $xiluuser = XilujobUser::get(['user_id'=>$this->auth->id]);
        if($xiluuser->enterprise_model->audit_status != 1) {
            $this->error('企业审核通过后方可操作');
        }
        $params = $this->request->post();
        $resume = ResumeModel::get($params['resume_id']);
        if($resume->personal->hide_mobile == 1){
            $this->error('用户已隐藏手机号');
        }
        try {
            $result = ResumeActionLog::record($xiluuser->enterprise_model->id, array_get($params,'user_id'), array_get($params,'resume_id'));
        }catch (Exception $e){
            $this->error($e->getMessage(),null,$e->getCode());
        }
        $resume = ResumeModel::get($params['resume_id']);
        $this->success('查询成功', ['mobile'=>$resume->personal->getData('mobile'),'email'=>$resume->personal->getData('email')]);
    }

    /**
     * 企业查看下载列表
     */
    public function download_list() {
        //$page = abs(intval($this->request->param('page')));
        //$page = $page < 1 ? 1:$page;
        $pagesize = abs(intval($this->request->param('pagesize')));
        $pagesize = $pagesize < 1 ? 10:$pagesize;
        $company = CompanyProfile::get(['user_id'=>$this->auth->id]);
        $downloadList = ResumeDownload::where('company_id', $company->id)
            ->order('id','desc')
            ->with('resume')
            //->limit(($page-1)*$pagesize, $pagesize)
            ->paginate($pagesize);
        foreach ($downloadList as $item) {
            //fixme: with嵌套
            $item->resume->relationQuery(['job_intention','personal','personal_tags']);
        }
        $this->success('查询成功', $downloadList);
    }

    public function poster_info($id) {
        $id = $this->request->param('id');
        $resume = ResumeModel::get($id);
        //if(!$resume->miniapp_code) {
            $wx = new WeixinMini();
            $uid = $this->auth->id;
            $xiluuser = XilujobUser::get(['user_id'=>$uid]);
            $page = "pages/company/talent_details";
            $res = $wx->getUnlimited("id=".$id."&uid=".$uid."&group=".$xiluuser->group_id,$page);
            if(!$res) $this->error('获取小程序二维码失败');
            $path = "/runtime/xilujob/resume/";
            if (!file_exists(ROOT_PATH . $path)) {
                @mkdir(ROOT_PATH . $path, 0777, true);
            }
            $filename = $resume->id.'.png';
            $qrcode = $path.$filename;
            file_put_contents(ROOT_PATH.$qrcode,$res);

            // 上传成功后该文件将被删除，请务必使用临时文件，这里$tempFile为你服务器准备上传的文件
            $tempFile = ROOT_PATH . $qrcode;
            $qrcode = (new Upload())->uploadApi($tempFile);
            $resume->save(['miniapp_code'=>cdnurl($qrcode,true)]);
        //}
        $text2 = $resume->personal->gender_text.'/'.
            $resume->personal->age.'/'.
            ($resume->personal->education_level?$resume->personal->education_level->name:'').'/'.
            ($resume->personal->work_experience?$resume->personal->work_experience->name.'工作经验':'');
        $text2 = preg_replace('/[\/]+/','/', $text2);
        $text3 = '';

        $this->success('',[
            'text1' => $resume->personal->realname,
            'text2'=>$text2,
            'tip'=>'长按识别二维码，查看简历详情',
            'text3' => $text3,
            'text4' =>"欢迎各位HR邀请面试",
            'img2'=>cdnurl($resume->miniapp_code,true),
            'img1'=>cdnurl($resume->personal->avatar?:$resume->personal->avatar,true)
        ]);
    }


    /**
     * 我看过的记录(仅企业)
     */
    public function my_look() {
        $company = CompanyProfile::get(['user_id'=>$this->auth->id]);
        $lists = ResumeModel::alias('resume')
            ->with(['job_intention','personal', 'personal_tags'])
            ->join('xilujob_resume_view_log log','resume.id=log.resume_id')
            ->where('log.company_id', $company->id)
            ->order('log.view_time','desc')
            ->field('log.view_time')
            ->paginate();
        $this->success('查询成功',$lists);
    }

    /**
     * 看过我的个人用户简历list(only for 企业)
     */
    public function look_my() {
        $paginator = ResumeModel::alias('resume')
            ->with(['job_intention', 'personal', 'personal_tags']);
        $xilujobuser = XilujobUser::get(['user_id'=>$this->auth->id]);
        switch ($xilujobuser->enterprise_group_id) {
            case XilujobUser::GROUP_COMPANY:
                $paginator->join('xilujob_company_view_log log','resume.user_id=log.user_id')
                    ->where('log.company_id', $xilujobuser->group_model->id);
                break;
        }
        $lists = $paginator->order('log.view_time','desc')
            ->field('log.view_time')
            ->paginate();
        $this->success('',$lists);
    }


    /**
     * 收藏列表
     */
    public function fav_list() {
        $company = CompanyProfile::get(['user_id'=>$this->auth->id]);
        $resumes = ResumeModel::with(['personal', 'job_intention','personal_tags'])
            ->join('xilujob_user_collection c', 'resume.id=c.collection_id')
            ->where('c.collection_type', UserCollection::TYPE_RESUME)
            ->where('c.user_id', $company->id)
            ->paginate();
        $this->success('',$resumes);
    }


    //求职意向
    public function job_intention(){
        $resume = \app\common\model\xilujob\Resume::getUserResume($this->auth->id);
        $job_intentions = $resume->jobIntention;
        $this->success('',$job_intentions);
    }


    public function resume_files(){
        $this->success('查询成功',ResumeFile::getResumeFiles($this->auth->id));
    }

    public function resume_files_prev(){
        $resumeId = $this->request->param('resume_id');
        $list = $resumeId?ResumeFile::field('id,name,file,file_ext')->where('resume_id',$resumeId)->select():null;
        if(is_null($list)){
            $this->error("参数错误");
        }
        $this->success('查询成功',$list);
    }

    /**
     * 上传附件
     */
    /**
     * 上传附件
     */
    public function add_files(){
        $files = $this->request->param('files/a');
        if(count($files)>15){
            $this->error('简历附件最多15份');
        }
        if($files) {
            $resume = \app\common\model\xilujob\Resume::getUserResume($this->auth->id);
            $memberId = Member::where('user_id',$this->auth->id)->value('id');
            $ids = [];
            foreach ($files as $file){
                $file['user_id'] = $this->auth->id;
                $file['member_id'] = $memberId;
                $file['resume_id'] = $resume->id;
                unset($file['createtime_text']);
                if(isset($file['id'])){
                    $ids[] = $file['id'];
                }else{
                    $result = ResumeFile::create($file);
                    $ids[] = $result['id'];
                }

            }
            unset($file);
            if($ids){
                ResumeFile::whereNotIn('id', $ids)->where('user_id', $this->auth->id)->delete();
            }

        }else {
            ResumeFile::where('user_id', $this->auth->id)->delete();
        }
        $this->success('附件简历保存成功',ResumeFile::getResumeFiles($this->auth->id));
    }

}